package cn.restcloud.springboot.listener;

import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import cn.restcloud.framework.core.container.BeanContainer;

/**
 * 当配置数据变化时用来刷新spring bean和restcloud bean的配置，并重新进行依赖注入
 * @author restcloud
 *
 */

@Configuration
public class RestCloudConfigRefreshAutoConfiguration {

	private static ContextRefresher springContextRefresher;
	private static ConfigurableEnvironment springEnvironment;
	private static ConfigurableListableBeanFactory springBeanFactory;
	
	/**
	 * 刷新所有java bean对像
	 * @throws Exception 
	 */
	public static void refresh() throws Exception {
		//自动刷新@RefreshScope注解的java bean
		if(springContextRefresher==null) {return;} //说明还没有实始化完成
		
		springContextRefresher.refresh(); //刷新

    	//spring重新注入
		int i=0;
    	 AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
         bpp.setAutowiredAnnotationType(Value.class);
         bpp.setBeanFactory(springBeanFactory);
         for (String name : springBeanFactory.getBeanDefinitionNames()) {
        	 Object  obj=springBeanFactory.getBean(name);
             bpp.processInjection(obj);
             i++;
         }
         
         //restcloud java bean自动刷新
        int total = BeanContainer.refresh();
//        PrintUtil.o("共刷新=="+total+"个java bean 对像 spring bean=="+i);
        
	}
	
    @Bean
    @ConditionalOnClass(ContextRefresher.class)
    public String restCloudconfigClientWatch(ContextRefresher contextRefresher, ConfigurableEnvironment environment, ConfigurableListableBeanFactory beanFactory) {
    	springContextRefresher=contextRefresher;
    	springEnvironment=environment;
    	springBeanFactory=beanFactory;
        return "restCloudconfigClientWatch";
    }

}